define([] , function(){
	var controller = function( $scope , $timeout , $ajax , $element , $ctx ){
		$scope.options = [] ;
		var handler = {
			init 	: 	function(){
				if( $scope.option && typeof $scope.option.change == 'function' ){
					$($element).bind('change' , function(  ){
						$scope.option.change( $( $element ).val() , $element , $scope.option ) ;
					});
				}
				return this ;
			},
			resetOptions : function(){
				var _this = this ;
				if( !$scope.option || !$scope.option.data ){
					$timeout( function(){
						$timeout( function(){
							$scope.options = _this.handleOptionData(  ) ;
						});
					});
					return ;
				}
				else if( typeof $scope.option.data  == 'string' ){
					this.loadData( $scope.option.data , function( data ){
						$timeout( function(){
							$scope.options = _this.handleOptionData( data ) ;
						});
					});
				}else if( $scope.option.data instanceof Array ){
					$timeout( function(){
						$scope.options = _this.handleOptionData( data ) ;
					});
				}
			},
			handleOptionData 	: 	function( data ){
				if( $ctx.debug )
					console.log('下拉框数据' , data ) ;

				var ops = [{
						id 	: 	'' ,
						name: 	'请选择'
					}] , keyName = $scope.option && $scope.option.key || 'id' , 
					valueName =  $scope.option && $scope.option.text || 'name';

				if( !data || !data.length )
					return ops;
				if( $scope.option && typeof $scope.option.handleData == 'function' )
					data = $scope.option.handleData( data ) ;

				data.forEach( function( v , k ){
					ops.push({
						id 	: 	util.format( keyName , v ) ,
						name : 	util.format( valueName , v )
					});
				});

				if( $ctx.debug )
					console.log('下拉框option数据' , ops ) ;
				return ops ;
			},
			loadData : function( url , then ){
				$ajax.get( url ).success( function( result ){
					if( result.code != 0 )
						return alert( result.message ) ;
					then( result.data ) ;
				});
			}
		}

		$scope.$watch('option.data' , function( n , o ){
			handler.resetOptions() ;
		} , true );

		$scope.$watch('data' , function( n , o ){
			if( typeof n == 'undefined' )
				$scope.data = '' ;
		} , true ) ;

		$timeout( function(){
			handler.init() ;
		});
	}
	app.register.directive('ngSelect' , function(){
		return {
			restrict 	: 	'E' ,
			replace 	: 	true ,
			scope 		: 	{
				option 	: 	'=option' ,
				data 	: 	'=data'
			},
			templateUrl : 	'assets/modules/ng-select/template.html' ,
			controller 	: 	controller 
		}
	});
});